<template>
  <div class="plane" id="plane">
    <img src="@/assets/images/plane.png" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      plane: null,
      situationIndex: -1,
      speedIndex: -1,
      balanceIndex: -1,
      requestAnimationFrameId: null,
      requestAnimationSpeedFrameId: null,
      requestAnimationBalanceFrameId: null,
      gamepads: [],
      gameContiner: null,
    };
  },
  computed: {
    ...mapGetters(["rockerSpeed"]),
  },
  mounted() {
    this.plane = document.getElementById("plane");
    const planeOffset = {
      planeOffsetX: this.plane.style.left,
      planeOffsetY: this.plane.style.top,
    };
    this.$store.commit("updateFlyDataKey", planeOffset);
    this.gameContiner = this.$parent.$el;
    window.addEventListener("gamepadconnected", this.gamepadConnected);
    window.addEventListener("gamepaddisconnected", this.gamepadDisconnected);
  },
  methods: {
    gamepadConnected(e) {
      this.gamepads.push(e.gamepad);
      this.updateControllerInfo();
      console.log("输出所有设备", this.gamepads);
    },
    gamepadDisconnected(e) {
      console.log("Gamepad disconnected from index " + e.gamepad.index);
      var index = this.gamepads.indexOf(e.gamepad);
      if (index !== -1) {
        this.gamepads.splice(index, 1);
        this.updateControllerInfo();
      }
    },
    updateControllerInfo() {
      for (var i = 0; i < this.gamepads.length; i++) {
        var gamepad = this.gamepads[i];
        if (gamepad.id.includes("Joystick")) {
          this.situationIndex = i;
          console.log("读取到方向控制器，此时i为：", i, this.situationIndex);
          this.startSituationGamepad();
          console.log("控制器类型: 方向控制器");
        } else if (gamepad.id.includes("Throttle")) {
          this.speedIndex = i;
          console.log("读取到速度控制器，此时i为：", i, this.speedIndex);
          this.startSpeedGamepad();
          console.log("控制器类型: 速度控制器");
        } else if (gamepad.id.includes("T-Pendular")) {
          this.balanceIndex = i;
          console.log("读取到平衡控制器，此时i为：", i, this.balanceIndex);
          this.startSituationBalanceGamepad();
          console.log("控制器类型: 平衡控制器");
        } else {
          console.log("控制器类型: 未知");
        }
      }
    },
    //平衡控制器开始方法
    startSituationBalanceGamepad() {
      console.log("开始轮询平衡控制器的输入");
      this.requestAnimationBalanceFrameId = requestAnimationFrame(
        this.balanceGamepad
      );
    },
    //平衡控制器停止方法
    stopSituationBalanceGamepad() {
      console.log("停止轮询平衡控制器的输入");
      cancelAnimationFrame(this.requestAnimationBalanceFrameId);
    },
    //方向控制器开始方法
    startSituationGamepad() {
      console.log("开始轮询方向控制器的输入");
      this.requestAnimationFrameId = requestAnimationFrame(this.pollGamepad);
    },
    //方向控制器停止方法
    stopSituationGamepad() {
      console.log("停止轮询方向控制器的输入");
      cancelAnimationFrame(this.requestAnimationFrameId);
    },
    //速度控制器开始方法
    startSpeedGamepad() {
      console.log("开始轮询速度控制器的输入");
      this.requestAnimationSpeedFrameId = requestAnimationFrame(
        this.speedGamepad
      );
    },
    //速度控制器停止方法
    stopSpeedGamepad() {
      console.log("停止轮询速度控制器的输入");
      cancelAnimationFrame(this.requestAnimationSpeedFrameId);
    },
    //平衡控制器方法
    balanceGamepad() {
      var gamepads = navigator.getGamepads();
      if (!gamepads || !gamepads[this.balanceIndex]) {
        console.log("平衡控制器未连接或无效，停止轮询", gamepads);
        this.stopSituationBalanceGamepad();
        return;
      }
      var gamepad = gamepads[this.balanceIndex];
      let axis = gamepad.axes[2].toFixed(2);
      this.$store.commit("setTroubdSpeed", axis);
      this.requestAnimationBalanceFrameId = requestAnimationFrame(
        this.balanceGamepad
      );
    },
    //方向控制器方法
    pollGamepad() {
      var gamepads = navigator.getGamepads();
      if (!gamepads || !gamepads[this.situationIndex]) {
        console.log("方向控制器未连接或无效，停止轮询", gamepads);
        this.stopSituationGamepad();
        return;
      }
      var gamepad = gamepads[this.situationIndex];
      var axisX = gamepad.axes[0];
      var axisY = gamepad.axes[1];
      this.moveBall(axisX, axisY);
      for (var j = 0; j < gamepad.buttons.length; j++) {
        var button = gamepad.buttons[j];
        if (button.pressed) {
          console.log("游戏方向控制器上的按钮 " + j + " 被按下");
        }
      }
      this.requestAnimationFrameId = requestAnimationFrame(this.pollGamepad);
    },
    //控制模型移动
    moveBall(axisX, axisY) {
      let rotateZ = axisX.toFixed(1) * 90;
      let rotateX = axisY.toFixed(1) * 30;
      document.documentElement.style.setProperty(
        "--rotateZ-plane",
        `${rotateZ}deg`
      );
      document.documentElement.style.setProperty(
        "--rotateX-plane",
        `${-rotateX}deg`
      );
      var newX = this.plane.offsetLeft + axisX * this.rockerSpeed;
      var newY = this.plane.offsetTop + axisY * this.rockerSpeed;
      newX = Math.max(
        0,
        Math.min(this.gameContiner.offsetWidth - this.plane.offsetWidth, newX)
      );
      newY = Math.max(
        0,
        Math.min(this.gameContiner.offsetHeight - this.plane.offsetHeight, newY)
      );
      this.plane.style.left = newX + "px";
      this.plane.style.top = newY + "px";
      const planeOffset = {
        planeOffsetX: newX.toFixed(2),
        planeOffsetY: newY.toFixed(2),
      };
      this.$store.commit("updateFlyDataKey", planeOffset);
    },
    //速度控制器方法
    speedGamepad() {
      var gamepads = navigator.getGamepads();
      if (!gamepads || !gamepads[this.speedIndex]) {
        console.log("速度控制器未连接或无效，停止轮询", gamepads);
        this.stopSpeedGamepad();
        return;
      }
      var gamepad = gamepads[this.speedIndex];
      var axisX = gamepad.axes[2];
      var axisY = gamepad.axes[5];
      axisY = ((-axisY + 1) * 5).toFixed(2);
      axisX = ((-axisX + 1) * 5).toFixed(2);
      this.$store.commit("setBgSpeed", axisX);
      console.log("axisX:", axisX);
      for (var j = 0; j < gamepad.buttons.length; j++) {
        var button = gamepad.buttons[j];
        if (button.pressed) {
          console.log("游戏速度控制器上的按钮 " + j + " 被按下");
        }
      }
      this.requestAnimationSpeedFrameId = requestAnimationFrame(
        this.speedGamepad
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.plane {
  width: 120px;
  height: 160px;
  position: absolute;
  left: 50%;
  bottom: 5%;
  transform: rotateZ(var(--rotateZ-plane));
  transition: transform 0.1s ease-in-out;
}

.plane img {
  width: 100%;
  height: 100%;
  transform: rotateX(var(--rotateX-plane));
}
</style>
